package com.ly.interceptor;

import com.ly.exception.BusinessException;
import com.ly.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    // 不拦截的api的静态集合
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/api/auth/login",  // 生产环境路径（Docker+Nginx）
            "/auth/login",
            "/pay/alipay"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        // 检查是否是无需验证的路径（如登录）
        if (isExcludePath(request.getRequestURI())) {
            return true;
        }

        // 从请求头获取token
        String token = jwtUtils.getTokenFromHeader(request);
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(401, "未提供认证Token");
        }

        try {
            // 验证token - 这里会进行完整的验证（签名+过期时间）
            Claims claims = jwtUtils.getClaimsByToken(token);

            // 额外的业务逻辑验证
            String userId = claims.getSubject();
            if (StringUtils.isBlank(userId)) {
                throw new BusinessException(401, "用户信息无效");
            }

            // 验证角色信息（可选）
            String role = (String) claims.get("role");
            if (StringUtils.isBlank(role)) {
                // 根据业务需求决定是否严格要求角色信息
                throw new BusinessException(401, "用户角色无效");
            }

            // 将用户信息存入request
            request.setAttribute("currentUserId", userId);
            request.setAttribute("currentUserRole", role);


        } catch (BusinessException e) {
            throw e; // 重新抛出，让全局异常处理器处理
        }

        return true;
    }

    private boolean isExcludePath(String requestURI) {
        return EXCLUDE_PATHS.stream().anyMatch(path ->
                requestURI.startsWith(path) || requestURI.equals(path)
        );
    }

}